﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;

namespace FlyingEye.Data
{
    public class FlyingEyeDbMigrationService : ITransientDependency
    {
        public ILogger<FlyingEyeDbMigrationService> Logger { get; set; }
        private readonly IDataSeeder _dataSeeder;
        private readonly IEnumerable<IFlyingEyeDbSchemaMigrator> _dbSchemaMigrators;

        public FlyingEyeDbMigrationService(
                    IDataSeeder dataSeeder,
                    IEnumerable<IFlyingEyeDbSchemaMigrator> dbSchemaMigrators)
        {
            _dataSeeder = dataSeeder;
            _dbSchemaMigrators = dbSchemaMigrators;
            Logger = NullLogger<FlyingEyeDbMigrationService>.Instance;
        }

        public async Task MigrateAsync()
        {
            Logger.LogInformation("Started database migrations...");
            await MigrateDatabaseSchemaAsync();
            await SeedDataAsync();
            Logger.LogInformation($"Successfully completed host database migrations.");
        }

        private async Task MigrateDatabaseSchemaAsync()
        {
            Logger.LogInformation(
                $"Migrating schema for host database...");

            foreach (var migrator in _dbSchemaMigrators)
            {
                await migrator.MigrateAsync();
            }
        }

        private async Task SeedDataAsync()
        {
            Logger.LogInformation($"Executing host database seed...");

            // 自动调用 IDataSeedContributor 的示例进行播种。
            await _dataSeeder.SeedAsync();
        }
    }
}
